"use client";

import useCategories from "@/app/hooks/categories.hook";
import { useNotifications } from "@/app/hooks/notification.hook";
import itemsService from "@/app/services/items.service";
import { useState } from "react";

export default function CategoriesPage() {
  const { showError, showSuccess } = useNotifications();
  const { categories, refresh } = useCategories();
  const [name, setName] = useState<string>("");
  const handleSubmit = async () => {
    if (name.trim().length < 1) return showError("Введите название категории");

    const _ = await itemsService.createCategory(name);
    await refresh();
    showSuccess("Категория успешно создана");
  };

  const handleDelete = async (id: number) => {
    try {
      await itemsService.deleteCategory(id);
      showSuccess("Категория успешно удалена");
      refresh();
    } catch (err) {
      showError(`Невозмонжо удалить категорию: ${err}`);
    }
  };

  return (
    <section className="manage" style={{ flex: 2 }}>
      <h1 className="heading">
        Управление <span>категориями</span>
      </h1>

      <div className="col" style={{ width: "30%" }}>
        <div className="row" style={{ alignItems: "flex-end" }}>
          <div className="item">
            <span>Наименование категории:</span>
            <div className="inputBox">
              <span className="fa  fa-asterisk"></span>
              <input
                value={name}
                onChange={(e) => setName(e.target.value)}
                type="text"
                placeholder="Наименование"
                name="name"
              />
            </div>
          </div>
          <input
            type="submit"
            value="Добавить"
            className="btn"
            onClick={handleSubmit}
            style={{
              height: "63px",
            }}
          />
        </div>
        <div className="col" style={{ marginTop: "35px", gap: "20px" }}>
          {categories.map((c) => (
            <div className="category" onClick={() => handleDelete(c.id)}>
              <span>{c.name}</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}
